package com.baseweb.webadmin.weixin.jssdk;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import com.baseweb.webadmin.weixin.utils.Constant;
import com.baseweb.webadmin.weixin.utils.HttpGetOrPost;

/**
 *  获取 Jsapi_ticket
 */
public class JsapiTicket {
	private   static  Logger logeer = LoggerFactory.getLogger(JsapiTicket.class);
	private   StringBuffer url  = new StringBuffer("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential");
	private   StringBuffer jsapUrl =  new StringBuffer("https://api.weixin.qq.com/cgi-bin/ticket/getticket?");

    public  String  getAccessToken() throws Exception{
    	
    	
    	String  access_token = null;
    	url.append("&appid=").append(Constant.WX_APPID).append("&secret=").append(Constant.WX_SECRET);
    	/***
    	 * 此处逻辑有错误，access_token不应该放在缓存里面，放在缓存中一直不变，3小时后还是那个值，但是已经过期
    	 * 外面的90分钟定时获取，其实已经相当于缓存了一次。
    	if(JsapiTicketCache.accessTokenMap.get(Constant.ACCESS_TOKEN) == null){
    		logeer.info("ACCESS_TOKEN已经失效");
    		//access_token 失效。获取access_token
    		JSONObject jsonobj =	HttpGetOrPost.sendGet(url.toString());
    		if(null != jsonobj && jsonobj.containsKey("access_token")){
    			access_token =   jsonobj.getString(Constant.ACCESS_TOKEN);
    		}
    		//缓存起来
        	JsapiTicketCache.accessTokenMap.put(Constant.ACCESS_TOKEN, access_token);
    	}else{
    		logeer.info("ACCESS_TOKEN在缓存中存在");
    		//如果缓存有
    		access_token =	(String) JsapiTicketCache.accessTokenMap.get(Constant.ACCESS_TOKEN);
    	}
    	*/
    	
    	//每90分钟直接获取最新的access_token即可
    	JSONObject jsonobj =	HttpGetOrPost.sendGet(url.toString());
		if(null != jsonobj && jsonobj.containsKey("access_token")){
			access_token =   jsonobj.getString(Constant.ACCESS_TOKEN);
		}
		logeer.info("获取的access_token：-->"+access_token);
        return  access_token;
    }
    
    /***
     * getJsapiTicket 
     * @return 正常返回ticket 异常返回null
     */
    public    String getJsapiTicket() {
    	
    	try {
			String access_token = getAccessToken();
			jsapUrl.append("access_token=").append(access_token).append("&type=jsapi");
			JSONObject jsonobj =	HttpGetOrPost.sendGet(jsapUrl.toString());
			logeer.info("获取的ticket：-->"+jsonobj);
			if(null != jsonobj){
				return   jsonobj.getString("ticket");
			}
		} catch (Exception e) {  
			logeer.error("获取Jsapi_ticket时出现异常", e);
		} 
    	return null;
    } 
}
